package com.handinfo.android.uicontrols;

import java.util.concurrent.CopyOnWriteArrayList;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Bitmap.Config;
import android.view.MotionEvent;

import com.handinfo.android.DWGameManager;
import com.handinfo.android.core.graphics.DWBitmap;
import com.handinfo.android.core.graphics.DWGraphics;
import com.handinfo.android.core.resource.DWSerializableFactory;
import com.handinfo.android.core.resource.ResHead;
import com.handinfo.android.core.resource.ResourceManager;
import com.handinfo.android.game.IIcon;
import com.handinfo.android.uicontrols.controls.DWControl;
import com.handinfo.android.uicontrols.controls.DWGrid;
import com.handinfo.android.uicontrols.controls.DWGrids;
import com.handinfo.android.uicontrols.controls.DWMessageBox;
import com.handinfo.android.uicontrols.controls.DWPopMenu;
import com.handinfo.android.utils.Tools;

public class DWControlsManager
{
	public long m_label = 0;
	public Bitmap[] img_biaoqing = null;
	public Bitmap[] img_select_rect = null;
	public Bitmap[] img_select_arc1 = null;
	public Bitmap[] img_select_arc2 = null;
	public Bitmap[] img_select_arc3 = null;
	private Bitmap img_bufImage = null;
	private DWGraphics g_bufImage = null;

	public static int CONTROL_WIDTH = 800;
	public static int CONTROL_HEIGHT = 480;

	public int m_timer = 0;//计时器
	public int m_render_num = 0;//绘制次数

	public DWGuideAttention m_guides = new DWGuideAttention();//用户引导对象
	public int m_guide_x = 0;
	public int m_guide_y = 0;
	public int m_guide_w = 0;
	public int m_guide_h = 0;
	public DWControl m_guide_control = null;

	/**
	 * 控件管理器
	 */
	private static DWControlsManager s_instance = null;

	/**
	 * 被拖拽的控件
	 */
	public DWControl m_drag_control = null;
	private int m_drag_x = 0;
	private int m_drag_y = 0;

	/**
	 * 游戏中UI控件容器,每个界面都是一个frame
	 */
	private CopyOnWriteArrayList<DWControl> m_controls = new CopyOnWriteArrayList<DWControl>();

	/**
	 * 创建或者得到一张控件图片
	 * @param path
	 * @return
	 */
	public Bitmap createControlImage(String path)
	{
		ResHead resHead = new ResHead();
		resHead.m_type = DWSerializableFactory.RESOURCE_TYPE_PNG;
		resHead.m_url = RES_PATH.concat(path).concat(DWSerializableFactory.EXTENSION_IMG);
		resHead.m_version = 1;
		return ((DWBitmap) ResourceManager.getInstance().loadResource(DWGameManager.getInstance().m_resourceStatic,
				resHead)).getImage();
	}

	/**
	 * 创建当前控件管理器
	 * @return
	 */
	public static DWControlsManager createDWControlsManager()
	{
		if (s_instance == null) {
			s_instance = new DWControlsManager();
		}
		return s_instance;
	}

	public void init()
	{
		if (img_bufImage == null) {
			img_bufImage = Bitmap.createBitmap(DWGameManager.Screen_Width, DWGameManager.Screen_Height, Config.RGB_565);
			g_bufImage = new DWGraphics(img_bufImage);
		}
		if (img_select_rect == null) {
			img_select_rect = new Bitmap[8];
			for (int i = 0; i < img_select_rect.length; i++) {
				img_select_rect[i] = createControlImage(RES_SELECT_RECT + i);
			}
		}

		if (img_select_arc1 == null) {
			img_select_arc1 = new Bitmap[4];
			for (int i = 0; i < img_select_arc1.length; i++) {
				img_select_arc1[i] = createControlImage("jinengxzk_" + (i + 1));
			}
		}

		if (img_select_arc2 == null) {
			img_select_arc2 = new Bitmap[4];
			for (int i = 0; i < img_select_arc2.length; i++) {
				img_select_arc2[i] = createControlImage("jinengmbk_" + (i + 1));
			}
		}
		
		if (img_select_arc3 == null) {
			img_select_arc3 = new Bitmap[4];
			for (int i = 0; i < img_select_arc3.length; i++) {
				img_select_arc3[i] = createControlImage("zhujiemianxzfg_" + (i + 1));
			}
		}
	}

	/**
	 * 获得当前控件管理器
	 * @return
	 */
	public static DWControlsManager getInstance()
	{
		if (s_instance == null) {
			s_instance = new DWControlsManager();
		}
		return s_instance;
	}

	/**
	 * 添加一个frame
	 * @param frame
	 */
	public void addControl(DWControl control)
	{
		if (control != null) {
			if (m_controls.contains(control)) {
				m_controls.remove(control);
			}
			if (control.getDisplayType() == DWControl.DISPLAY_TYPE_SCALING) {
				control.setScaling(true);
			}
			control.setID(m_controls.size() * 10000);
			int size = m_controls.size();
			if (size > 0) {
				DWControl temp = null;
				if (!control.getTop()) {
					for (int i = size - 1; i > -1; i--) {
						temp = m_controls.get(i);
						if (!temp.getTop()) {
							m_controls.add(i + 1, control);
							return;
						}
					}
				}
			}
			m_controls.add(control);
		}
	}

	/**
	 * 检测控件管理器中是否有此控件
	 * @param control
	 * @return
	 */
	public boolean contains(DWControl control)
	{
		if (control != null) {
			return m_controls.contains(control);
		}
		return false;
	}

	/**
	 * 将此控件置顶
	 * @param control
	 */
	public void topControl(DWControl control)
	{
		if (contains(control)) {
			m_controls.remove(control);
			m_controls.add(control);
		}
	}

	/**
	 * 移除一个frame
	 * @param frame
	 */
	public void removeControl(DWControl control)
	{
		if (control != null) {
			if (control.getDisplayType() == DWControl.DISPLAY_TYPE_SCALING) {
				control.setScaling(false);
			}
			m_controls.remove(control);
		}
	}

	/**
	 * 移除所有控件
	 */
	public void removeAllControl()
	{
		m_controls.clear();
	}

	/**
	 * 移除其他界面,只保留第一层界面
	 */
	public void removeOtherControl()
	{
		if (m_controls.size() > 1) {
			DWControl control = m_controls.get(0);
			m_controls.clear();
			m_controls.add(control);
		}
	}

	/**
	 * 通过索引查找控件容器中的控件
	 * @param index
	 * @return
	 */
	public DWControl getFrameByIndex(int index)
	{
		if (index >= 0 && index < m_controls.size()) {
			return m_controls.get(index);
		}
		return null;
	}

	/**
	 * 通过ID查找控件容器中的控件
	 * @param id
	 * @return
	 */
	public DWControl getControlByID(int id)
	{
		DWControl control = null;
		for (int i = 0; i < m_controls.size(); i++) {
			control = m_controls.get(i);
			if (control.equalsID(id)) {
				break;
			}
		}
		return control;
	}

	/**
	 * 绘制
	 * @param g
	 */
	public void paint(DWGraphics g)
	{
		DWControl control = null;
		for (int i = 0; i < m_controls.size(); i++) {
			try {
				control = m_controls.get(i);
				if (control.getDisplayType() == DWControl.DISPLAY_TYPE_SCALING && control.getScaling()
						&& control.isScaling()) {
					img_bufImage.eraseColor(0x00000000);
					control.render(g_bufImage);
					float value = control.getScalingValue();
					g.setClip(0, 0, DWGameManager.Screen_Width, DWGameManager.Screen_Height);
					g.drawBitmap(img_bufImage, DWGameManager.Screen_Width / 2, DWGameManager.Screen_Height / 2,
							img_bufImage.getWidth() * value, img_bufImage.getHeight() * value, Tools.HCENTER_VCENTER);
				}
				else {
					if (control.isShow()) {
						control.render(g);
					}
				}
			}
			catch (Exception e) {
				Tools.debug(e);
			}
		}
		paintDargControl(g);
	}
	
	/**
	 * 绘制
	 * @param g
	 */
	public void paintMessageBox(DWGraphics g)
	{
		DWControl control = null;
		for (int i = 0; i < m_controls.size(); i++) {
			try {
				control = m_controls.get(i);
				if (control.isShow() && control instanceof DWMessageBox) {
					control.render(g);
				}
			}
			catch (Exception e) {
				Tools.debug(e);
			}
		}
	}

	/**
	 * 绘制拖拽的控件
	 * @param g
	 */
	private void paintDargControl(DWGraphics g)
	{
		if (m_drag_control != null && (m_drag_x > 0 || m_drag_y > 0)) {
			Object drag_obj = null;
			int w = 0;
			int h = 0;
			if (m_drag_control instanceof DWGrids) {
				DWGrids grids = (DWGrids) m_drag_control;
				DWGrid grid = grids.m_grids.get(grids.getTouchIndex());
				w = grid.getShowWidth();
				h = grid.getShowHeight();
				if (grid != null) {
					drag_obj = grid.m_data;
				}
			}
			else if (m_drag_control instanceof DWGrid) {
				DWGrid grid = (DWGrid) m_drag_control;
				w = grid.getShowWidth();
				h = grid.getShowHeight();
				drag_obj = grid.m_data;
			}
			if (drag_obj != null && drag_obj instanceof IIcon) {
				g.setClip(0, 0, DWGameManager.Screen_Width, DWGameManager.Screen_Height);
				g.setColor(Color.GREEN);
				g.setAlpha(0xFF);
				g.drawRect(m_drag_x - (int) (w * ICON_SCALE / 2) - 15, m_drag_y - (int) (h * ICON_SCALE / 2) - 15,
						(int) (w * ICON_SCALE + 30), (int) (h * ICON_SCALE + 30));
				g.drawLine(m_drag_x, (int) (m_drag_y - h * ICON_SCALE), 0, (int) (h * ICON_SCALE * 2));
				g.drawLine((int) (m_drag_x - w * ICON_SCALE), m_drag_y, (int) (w * ICON_SCALE * 2), 0);
				((IIcon) drag_obj).drawIcon(g, m_drag_x, m_drag_y, w, h, ICON_SCALE, ICON_SCALE, Tools.HCENTER_VCENTER);
			}
		}
	}

	private final float ICON_SCALE = 1.5f;
	private final int m_rect_all = 8;
	private final int m_rect_speed = 1;
	private final int SR_UP = 0;
	private final int SR_LEFT_UP = 1;
	private final int SR_LEFT = 2;
	private final int SR_LEFT_DOWN = 3;
	private final int SR_DOWN = 4;
	private final int SR_RIGHT_DOWN = 5;
	private final int SR_RIGHT = 6;
	private final int SR_RIGHT_UP = 7;

	public void paintSelectRect(DWGraphics g, int x, int y, int w, int h)
	{
		w -= 10;
		h -= 10;
		x += 5;
		y += 5;
		int way = (m_timer % (m_rect_all * m_rect_speed)) / m_rect_speed;
		switch (way) {
			case SR_UP:
			case SR_DOWN:
				g.drawBitmap(img_select_rect[SR_UP], x + w / 2, y, Tools.HCENTER_VCENTER);
				g.drawBitmap(img_select_rect[SR_DOWN], x + w / 2, y + h, Tools.HCENTER_VCENTER);
				break;
			case SR_LEFT:
			case SR_RIGHT:
				g.drawBitmap(img_select_rect[SR_LEFT], x, y + h / 2, Tools.HCENTER_VCENTER);
				g.drawBitmap(img_select_rect[SR_RIGHT], x + w, y + h / 2, Tools.HCENTER_VCENTER);
				break;
			case SR_LEFT_DOWN:
			case SR_RIGHT_UP:
				g.drawBitmap(img_select_rect[SR_LEFT_DOWN], x + 9, y + h - 6, Tools.HCENTER_VCENTER);
				g.drawBitmap(img_select_rect[SR_RIGHT_UP], x + w - 9, y + 6, Tools.HCENTER_VCENTER);
				break;
			case SR_LEFT_UP:
			case SR_RIGHT_DOWN:
				g.drawBitmap(img_select_rect[SR_LEFT_UP], x + 6, y + 9, Tools.HCENTER_VCENTER);
				g.drawBitmap(img_select_rect[SR_RIGHT_DOWN], x + w - 6, y + h - 9, Tools.HCENTER_VCENTER);
				break;
		}
	}

	private final int m_arc1_all = 4;
	private final int m_arc1_speed = 2;

	public void paintSelectArc1(DWGraphics g, int x, int y, int w, int h)
	{
		int way = (m_timer % (m_arc1_all * m_arc1_speed)) / m_arc1_speed;
		g.drawBitmap(img_select_arc1[way], x + w / 2, y + h / 2, Tools.HCENTER_VCENTER);
	}

	private final int m_arc2_all = 4;
	private final int m_arc2_speed = 2;

	public void paintSelectArc2(DWGraphics g, int x, int y, int w, int h)
	{
		int way = (m_timer % (m_arc2_all * m_arc2_speed)) / m_arc2_speed;
		g.drawBitmap(img_select_arc2[way], x + w / 2, y + h / 2, Tools.HCENTER_VCENTER);
	}
	
	private final int m_arc3_all = 4;
	private final int m_arc3_speed = 2;

	public void paintSelectArc3(DWGraphics g, int x, int y, int w, int h)
	{
		int way = (m_timer % (m_arc3_all * m_arc3_speed)) / m_arc3_speed;
		g.drawBitmap(img_select_arc3[way], x + w / 2, y + h / 2, Tools.HCENTER_VCENTER);
	}


//	public static boolean checkObjectNull(Object obj) {
//		if (obj != null) {
//			if (obj instanceof Cell) {
//				if (((Cell)obj).m_item != null) {
//					return true;
//				}
//			} else if (obj instanceof Tianming) {
//				Tianming tm = ((Tianming)obj);
//				if (tm != null) {
//					return true;
//				}
//			} else if (obj instanceof Item) {
//				Item item = (Item)obj;
//				if (item != null) {
//					return true;
//				}
//			}
//		}
//		return false;
//	}

	/**
	 * 逻辑
	 */
	public void logic()
	{
		DWControl deal = null;
		DWControl control = null;
		for (int i = 0; i < m_controls.size(); i++) {
			try {
				control = m_controls.get(i);
				control.logic();
				if (control.getDeal()) {
					deal = control;
				}
			}
			catch (Exception e) {
				Tools.debug(e);
			}
		}
		if (deal != null) {
			deal.setDeal(false);
			deal.destroy();
			m_controls.remove(deal);
			deal = null;
		}
		m_guides.waitGuide();

		if (++m_timer > 1000000) {
			m_timer = 0;
		}
	}

	public void execute(DWGraphics g)
	{
		paint(g);
		logic();
	}

	/**
	 * 设置拖拽的控件
	 * @param control
	 * @param x
	 * @param y
	 */
	public void setDragControl(DWControl control)
	{
		m_drag_control = control;
	}

	/**
	 * 得到拖拽的控件
	 * @return
	 */
	public DWControl getDragControl()
	{
		return m_drag_control;
	}

	/**
	 * 此控件是否需要背景蒙版
	 * @param control
	 * @return
	 */
	public static boolean isMatte(DWControl control)
	{
		if (control instanceof DWMessageBox
				|| control instanceof DWPopMenu) {
			return true;
		}
		return false;
	}

	public void setGuidePoint(int x, int y, int w, int h)
	{
		m_guide_x = x;
		m_guide_y = y;
		m_guide_w = w;
		m_guide_h = h;
	}

	/**
	 * 绘制一个背景蒙版
	 * @param g
	 * @return
	 */
	public static void renderMatte(DWGraphics g)
	{
		g.setClip(0, 0, DWGameManager.Screen_Width, DWGameManager.Screen_Height);
		g.setColor(0x88000000);
		g.fillRect(0, 0, DWGameManager.Screen_Width, DWGameManager.Screen_Height);
	}

	/** 滚动条颜色 */
	public static final int[] COLOR_SCROLL_BAR = { 0xFF520602, 0xFFFFD449, 0xFF966301, 0xFF520602 };

	public static final int COLOR_STROKE = 0xFF0F0601;

//	public static final int H_ALL_FONT = (int) DWFont.getDefaultFont().getFontHeight();
//	public static final int H_HALF_FONT = H_ALL_FONT / 2;

	private final String RES_PATH = "/img/newui/";
	public static final String RES_TITLE_SIDE = "biaotikuang_1";
	public static final String RES_TITLE_MIDDLE = "biaotikuang_2";
	public static final String RES_BIAOQING = "biaoqing";
//	public static final String RES_ITEM_OPEN = "item_open";
//	public static final String RES_ITEM_CLOSE = "item_close";
//	public static final String RES_SHORTCUTS = "label_rect_skill";
//	public static final String RES_SCROLLBAR_HEAD = "drag_top";
//	public static final String RES_SCROLLBAR_MARK = "xialatiaoxiaozhu";
//	public static final String RES_SCROLLBAR_HEAD_UP = "huadongjiantoushang";
//	public static final String RES_SCROLLBAR_HEAD_DOWN = "huadongjiantouxia";
	public static final String RES_SCROLLBAR_MARK = "huadongkuai";
	public static final String RES_SCROLLBAR_RECT = "huadongtiao";
	public static final String RES_SELECT_RECT = "select_rect_";
	public static final String RES_CORNER_LU = "UIkz-1";
	public static final String RES_CORNER_LD = "UIkz-2";
	public static final String RES_CORNER_RD = "UIkz-3";
	public static final String RES_CORNER_RU = "UIkz-4";

//	/** 网格样式 背包样式 有锁定图标 */
//	public static final byte GRID_STYLE_BACKPACK = 0;
//	/** 网格样式 快捷栏样式 无锁定图标*/
//	public static final byte GRID_STYLE_SHORTCUTS = 1;

	//////////////////////////////////////////////////////
	//	触摸方法
	//////////////////////////////////////////////////////
	/**
	 * 按下
	 */
	public boolean doDown(PointF point)
	{
		for (int i = m_controls.size() - 1; i >= 0; i--) {
			try {
				if (m_controls.get(i).doDown(point)) {
					return true;
				}
			}
			catch (Exception e) {
				Tools.debug(e);
				return true;
			}
		}
		return false;
	}
	/**
	 * 单击触发
	 * @param pointX
	 * @param pointY
	 */
	public boolean doClick(float pointX, float pointY)
	{
		for (int i = m_controls.size() - 1; i >= 0; i--) {
			DWControl control = m_controls.get(i);
			try {
				if (control.doClick(pointX, pointY)) {
					return true;
				}
			}
			catch (Exception e) {
				Tools.debugPrintln(" control = " + control);
				Tools.debug(e);
				return true;
			}
			if (isMatte(m_controls.get(i))) {
				break;
			}
		}
		return false;
	}

	/**
	 * 双击
	 */
	public boolean doDoubleClick(PointF point)
	{
		for (int i = m_controls.size() - 1; i >= 0; i--) {
			try {
				if (m_controls.get(i).doDoubleClick(point)) {
					return true;
				}
			}
			catch (Exception e) {
				Tools.debug(e);
				return true;
			}
		}
		return false;
	}

	/**
	 * 长按
	 */
	public boolean doLongPress(PointF point)
	{
		for (int i = m_controls.size() - 1; i >= 0; i--) {
			try {
				if (m_controls.get(i).doLongPress(point)) {
					return true;
				}
			}
			catch (Exception e) {
				Tools.debug(e);
				return true;
			}
		}
		return false;
	}

	/**
	 * 按下移动
	 * @param start
	 * @param end
	 * @param distanceX
	 * @param distanceY
	 */
	public boolean doScroll(PointF start, PointF end, float distanceX, float distanceY)
	{
		for (int i = m_controls.size() - 1; i >= 0; i--) {
			try {
				if (m_controls.get(i).doScroll(start, end, distanceX, distanceY)) {
					return true;
				}
			}
			catch (Exception e) {
				Tools.debug(e);
				return true;
			}
			if (isMatte(m_controls.get(i))) {
				break;
			}
		}
		return false;
	}

	/**
	 * 长按移动
	 */
	public boolean doLongScroll(PointF start, PointF end, float distanceX, float distanceY)
	{
		if (m_drag_control != null) {
			m_drag_x = (int) (end.x - 48);
			m_drag_y = (int) (end.y - 48);
			return true;
		}
		for (int i = m_controls.size() - 1; i >= 0; i--) {
			try {
				if (m_controls.get(i).doLongScroll(start, end, distanceX, distanceY)) {
					return true;
				}
			}
			catch (Exception e) {
				Tools.debug(e);
				return true;
			}
		}

		return false;
	}

	/**
	 * 点击移动抬起
	 */
	public boolean doFling(PointF start, PointF end, float velocityX, float velocityY)
	{
		for (int i = m_controls.size() - 1; i >= 0; i--) {
			try {
				if (m_controls.get(i).doFling(start, end, velocityX, velocityY)) {
					return true;
				}
			}
			catch (Exception e) {
				Tools.debug(e);
				return true;
			}
		}
		return false;
	}

	/**
	 * 长按移动抬起
	 */
	public boolean doDrag(PointF start, PointF end, float velocityX, float velocityY)
	{
		for (int i = m_controls.size() - 1; i >= 0; i--) {
			try {
				if (m_drag_control != null) {
					DWLongListener ll = m_drag_control.getLongListener();
					if (ll != null) {
						ll.OnLong(false);
					}
					if (m_controls.get(i).doDrag(start, new PointF(m_drag_x, m_drag_y), velocityX, velocityY)) {
						m_drag_control = null;
						m_drag_x = 0;
						m_drag_y = 0;
						return true;
					}
				}
				else {
					if (m_controls.get(i).doDrag(start, end, velocityX, velocityY)) {
						m_drag_control = null;
						m_drag_x = 0;
						m_drag_y = 0;
						return true;
					}
				}
			}
			catch (Exception e) {
				Tools.debug(e);
				return true;
			}
		}
		m_drag_control = null;
		m_drag_x = 0;
		m_drag_y = 0;
		return false;
	}

	public boolean onTouch(MotionEvent event, PointF point)
	{
		for (int i = m_controls.size() - 1; i >= 0; i--) {
			try {
				if (m_controls.get(i).onTouch(event, point)) {
					return true;
				}
			}
			catch (Exception e) {
				Tools.debug(e);
				return true;
			}
		}
		return false;
	}
}
